package com.admin.security.filter.token;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import com.admin.security.constant.SecurityConstant;
import com.admin.security.service.JwtTokenService;
import com.admin.utils.constant.GlobleSysUser;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * jwt登录token校验
 * 
 * @author monxz
 *
 * @date 2019年10月25日
 */

public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
	
	private JwtTokenService jwtTokenService;
	
	
	
	public JWTAuthenticationFilter(AuthenticationManager authenticationManager,JwtTokenService jwtTokenService) {
		super(authenticationManager);
		this.jwtTokenService = jwtTokenService;

	}

	/**
	 * 验证token （可选）.
	 * 
	 * @see org.springframework.security.web.authentication.www.BasicAuthenticationFilter#doFilterInternal(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String header = request.getHeader(SecurityConstant.token_header);				
		if (header == null) {
			chain.doFilter(request, response);
			return;
		}
		
		GlobleSysUser 	user = jwtTokenService.dealUser(header);
		if(user != null) {
			UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, simPleGrans(user));
			SecurityContextHolder.getContext().setAuthentication(authentication);
			response.setHeader(SecurityConstant.token_header, user.getUserId()+"@"+user.getLastTime());
			chain.doFilter(request, response);
		}else {
			response.setHeader(SecurityConstant.token_header, "");
			chain.doFilter(request, response);
			return;
		}
		
		
	}
	
	
	/**
	 * 单独处理权限问题，处理由于内部类得序列化问题
	 * @param uncomStr
	 * @return
	 */

	private List<GrantedAuthority>  simPleGrans(GlobleSysUser user){
		List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
		for(String perm : user.getPermissions()) {
			if(perm != null && !perm.isEmpty()) {
				grantedAuthorities.add( new SimpleGrantedAuthority(perm));
			}
			
		}		
		return grantedAuthorities;
	}


}
